<?php

namespace App\Http\Controllers\OA;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Logic\UserLogic;
use App\Imports\TokenImport;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\IOFactory;

class TestController extends Controller
{
    private $log = '';

    public function index()
    {

        dd(1111);
        //$this->getUser();
        //$this->currency();
    }

    function Pool(Request $request){
        $this->log = new Logger('testPoolResponse');
        $streamHander1 = new StreamHandler(storage_path('logs/testPoolResponse.log'), Logger::INFO);
        $this->log->pushHandler($streamHander1);

        $user = $request->input('user');
        $this->log->info('当前请求的用户是: '.$user);
        ret_json('ok','ok',['user'=>$user]);
    }

    function getUser()
    {
        $logic = new UserLogic();
        $logic->getUserInfo(13);
    }

    function currency()
    {
        $html = file_get_contents(storage_path('json/html.txt'));

        $preg='/<a .*?href="(.*?)".*?></a>/is';
        //$preg='/(\d+)\.(\d+)/is';
        preg_match_all($preg,$html,$match);
        dd($match);
    }

    public function excelImport(Request $request)
    {
        if($request->hasFile('excel')){
            $originalName = $request->file('excel')->getClientOriginalName(); // 文件原名
            $request->file('excel')->move('./Uploads',$originalName); //上传文件移动至指定目录
            $path = './Uploads/'.$originalName;
            $data = Excel::toArray(new TokenImport() , $path);
            $data = $data[0];
            $shop_list = array_filter(array_values($data[0]));
            unset($shop_list[0],$data[0]);
            $shops = [];
                foreach ($data as $val){
                    foreach ($shop_list as $shop){
                        if($val[0]) $shops[] = 'lazada' . '-' . $val[0] . '-' . $shop;
                    }
                }
            $shops = array_chunk($shops,6);
            $data2 = array_chunk($data,2);
            $token_list = [];
            foreach ($data2 as $k1 => $val){
                    for($j = 1;$j < count($val[0]);$j++){
                        if($val[0][$j] && $val[1][$j]){
                            $token_arr = explode(':',$val[0][$j]);
                            $refresh_arr = explode(':',$val[1][$j]);
                            $token_list[$k1][$j]['access_token'] = trim($token_arr[1]);
                            $token_list[$k1][$j]['refresh_token'] = trim($refresh_arr[1]);
                        }else{
                            $token_list[$k1][$j]['access_token'] = $val[0][$j];
                            $token_list[$k1][$j]['refresh_token'] = $val[1][$j];
                        }

                    }
            }
            $shop_token = [];
            for($i = 0;$i < count($shops);$i++){
                for($j = 0;$j < count($shops[0]);$j ++){
                   $shop_key = $shops[$i][$j];
                   $shop_val = $token_list[$i][$j + 1];
                   $shop_token[$shop_key] =  $shop_val;
                }
            }
            dd($shop_token);
        }
    }


    // 模版导出(读写)

    /**
     * @throws Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    public function templateExport($templateFile)
    {
        // $template_path = __DIR__ . '/PayrollTemplate.xls';
        // 读取模板
        $spreadsheet = IOFactory::load($templateFile);

        // 以下代码行将活动工作表索引设置为第一个工作表：设置Excel Sheet
        $spreadsheet->setActiveSheetIndex(0);

        // 指向激活的工作表
        $worksheet = $spreadsheet->getActiveSheet();

        $worksheet->getCell('A1')->setValue('John');
        $worksheet->getCell('B1')->setValue('Smith');

        // 样式设置 加边框
        $styleThinBlackBorderOutline = array(
            'borders' => [
                'allBorders' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
                    'color' => ['argb' => '666666'],
                ],
            ]
        );
        $worksheet->getStyle('A6:H' . 10)->applyFromArray($styleThinBlackBorderOutline);

        // 结束 进行导出
        ob_end_clean(); // 清空（擦除）缓冲区并关闭输出缓冲
        ob_start(); // 打开输出控制缓冲

        $date = date("Ymd", time());
        $listname = 'hello' . $date;

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $listname . '.xlsx"');
        header('Cache-Control: max-age=0');

        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');

    }



}
